package com.lsongh.springboot2.controller;

import com.lsongh.springboot2.entity.Result;
import com.lsongh.springboot2.utils.ResultUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;

@RestController
public class UploadController {


    @PostMapping("upload/img")
    public Result<String> uploadImg(@RequestBody MultipartFile[] img){
        //上传图片设置
        String savePath = "E:\\project-sctu-2019\\sctu-2019-code\\serve\\springboot2\\target\\classes\\static\\uploadImg";
        String savePath1 = "E:\\project-sctu-2019\\sctu-2019-code\\serve\\springboot2\\src\\main\\resources\\static\\uploadImg";
        String newFileName = null;
        String filePath = null;
        String filePath1 = null;
        String result="";
        int size = 0;
        String suffixName = null;
        for (MultipartFile file : img) {
            if (file != null && !file.isEmpty()) {
                //获取文件名称
                String fileName = file.getOriginalFilename();
                suffixName = fileName.substring(fileName.indexOf(".") + 1);  //获取后缀名
                size = (int) file.getSize(); //图片大小
                newFileName = System.currentTimeMillis() + "." + suffixName;   //新文件名称
                filePath = savePath + "\\" + newFileName;   //新文件路劲
                filePath1 = savePath + "\\" + newFileName;   //新文件路劲
                result ="uploadImg/" + newFileName ;
                // user.setImg("uploadImg/" + newFileName);
                //获取存储文件路径

                java.io.File fileDir = new java.io.File(savePath);
                java.io.File fileDir1 = new java.io.File(savePath1);
                if (!fileDir.exists())
                    fileDir.mkdirs();
                if (!fileDir1.exists())
                    fileDir1.mkdirs();
                }
                FileOutputStream fos = null;
                FileOutputStream fos1 = null;
                try {
                    fos = new FileOutputStream(filePath);
                    fos.write(file.getBytes());
                    fos.flush();

                    fos1 = new FileOutputStream(filePath1);
                    fos1.write(file.getBytes());
                    fos1.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();

                    }
                }
            }
        return ResultUtil.success(result);
    }
}
